package com.zzh.partnersys.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP压缩工具类
 *
 * @author zzh
 */
@Slf4j
public class GzipUtil {

    /**
     * 压缩数据
     *
     * @param data 原始数据
     * @return 压缩后的字节数组
     */
    public static byte[] compress(String data) {
        if (data == null || data.isEmpty()) {
            return new byte[0];
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
            gzos.write(data.getBytes("UTF-8"));
            gzos.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("GZIP压缩失败", e);
            throw new RuntimeException("GZIP压缩失败", e);
        }
    }

    /**
     * 解压数据
     *
     * @param compressedData 压缩后的字节数组
     * @return 解压后的字符串
     */
    public static byte[] decompress(byte[] compressedData) {
        if (compressedData == null || compressedData.length == 0) {
            return new byte[0];
        }

        try (ByteArrayInputStream bais = new ByteArrayInputStream(compressedData);
             GZIPInputStream gzis = new GZIPInputStream(bais);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("GZIP解压失败", e);
            throw new RuntimeException("GZIP解压失败", e);
        }
    }
}

